Component({
  /**
   * 组件的属性列表
   */
  properties: {
    cleft4: {
      type:Number,
      value: -1000
    },
    cndUrl:{
      type: String,
      value: ""
    },
    cshowBtn: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    toolSel: 3,
    cwidth:0,
    cheight:0,
    ctx1: "",
    sx1: 0,
    xy1: 0,
    mx1: 0,
    my1: 0,
    
    color: ["#f1d82c", "#c0cd25", "#8fb525", "#62a131", "#2c913d", "#177e77", "#106591", "#145294", "#334b90", "#5d2f81", "#761e71", "#a0185e", "#bf1942", "#d95721", "#e5881d", "#ecb722"],
    dcolorIndex: '',
    scolor: 'none',
    
    dcolor: "#000000",
    saveColor: "#000000",
    lineWidth: 1,
    cLineWidth: 6,

    getCanvas: '',
    canvansBg: '',
    xpc: false,
    moveLock: false,
    curTop: 0,


    bgarr:[
      getApp().domainName + "img/mh/1.jpg",
      getApp().domainName + "img/mh/2.jpg",
      getApp().domainName + "img/mh/3.jpg",
      getApp().domainName + "img/mh/4.jpg",
      getApp().domainName + "img/mh/5.jpg",
      getApp().domainName + "img/mh/6.jpg",
      getApp().domainName + "img/mh/7.jpg"
    ],
    newbgarr:[],
    picNum:0
  },
  ready() {
   var _this = this;
    var query = wx.createSelectorQuery().in(this);
    query.select('.chuabu1').boundingClientRect(function (rect) {
      console.log(rect)
      _this.setData({
        cwidth: rect.width,
        cheight: rect.height,
      })
      if (rect.width > rect.height) {
        _this.setData({
          curTop: -(rect.width - rect.height) / 2
        })

      }
     
    }).exec();
    //画布一
    this.ctx1 = wx.createCanvasContext("chuabu1", this);
    this.ctx2 = wx.createCanvasContext("chuabusave", this);
    this.ctx3 = wx.createCanvasContext("saveLocal", this);

    // this.ctx1.setFillStyle('#ffffff')
    // this.ctx1.fillRect(0, 0, 640, 640)
    // this.ctx1.draw(true)
    this.ctx1.setStrokeStyle(this.data.dcolor);
    this.ctx1.setLineWidth(this.data.cLineWidth);
    this.ctx1.setLineCap("round")
    console.log(123)


    this.saveToLocalPic(function (o) {
      //console.log(o)
      _this.setData({
        newbgarr: o
      }, function () {
        // _this.drawImgfn(0)
        // _this.changeCbg(0)
        _this.createImg()
      })
    })
   
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeCbg(n) {
      var _this = this;
      this.setData({
        getCanvas: this.data.newbgarr[n]
      })


    },
    changeLeft() {
      var _this = this;
      var picNum = parseInt(this.data.picNum) - 1;
      var len = this.data.newbgarr.length;

      picNum = picNum < 0 ? len - 1 : picNum;
      console.log(picNum)
      this.setData({
        picNum: picNum,
        toolSel: 3,
        dcolor: "#000000",
        saveColor: "#000000",

      }, function () {
        // getApp().selType = picNum;
        _this.changeCbg(picNum)
        //_this.drawImgfn(picNum)

      })
      _this.ctx1.globalCompositeOperation = 'source-over';
      _this.ctx1.clearRect(0, 0, 750, 750)
      _this.ctx1.draw(true)
      _this.ctx2.clearRect(0, 0, 750, 750)
      _this.ctx2.draw(true)
      _this.ctx3.clearRect(0, 0, 750, 750)
      _this.ctx3.draw(true)
    },
    changeRight() {
      var _this = this;
      var picNum = parseInt(this.data.picNum) + 1;
      var len = this.data.newbgarr.length;

      picNum = picNum >= len ? 0 : picNum;

      console.log(picNum)
      this.setData({
        picNum: picNum,
        toolSel: 3,
        dcolor: "#000000",
        saveColor: "#000000",
      }, function () {
        //getApp().selType = picNum;
        _this.changeCbg(picNum)
        //_this.drawImgfn(picNum)

      })

      _this.ctx1.globalCompositeOperation = 'source-over';
      _this.ctx1.clearRect(0, 0, 750, 750)
      _this.ctx1.draw(true)
      _this.ctx2.clearRect(0, 0, 750, 750)
      _this.ctx2.draw(true)
      _this.ctx3.clearRect(0, 0, 750, 750)
      _this.ctx3.draw(true)
    },
    drawImgfn(n){
      var img = this.data.newbgarr[n]
      this.ctx1.drawImage(img, 0, this.data.curTop, this.data.cwidth, this.data.cwidth);
      this.ctx1.draw(true)
    },
    saveToLocalPic(fn) { // 下载图片到本地 
      var _this = this;
      var bgarr = _this.data.bgarr;
      var imglen = bgarr.length;
      var newbgarr = [];
      var i = 0;

      var arr = savePic(bgarr[i])
      
      function savePic(path) {
        wx.downloadFile({
          url: path,
          success(res) {
            //console.log(res)
            if (res.statusCode === 200) {

              //console.log(res.tempFilePath);
              newbgarr.push(res.tempFilePath);
              //console.log(newCreatePicArr)
              i++;
              if (i == imglen) {
                console.log("图片下载完成", newbgarr);
                if (fn) {
                  fn(newbgarr);
                }
                //_this.createPicFn(newCreatePicArr);
              } else {
                savePic(bgarr[i])
              }

            }
          }
        })
      }

    },
    getColorfn(e) { // 选择颜色
      var color = e.target.dataset.color;
      var index = e.target.dataset.index +1;
      console.log(e.target.dataset.index)
      this.setData({
        dcolor: color,
        scolor: color,
        //showColor: false,
        dcolorIndex: index
      })
    },
    careafn(e) { // 笔触大小
      //console.log(e.detail);
      var linewidth = this.data.lineWidth + parseInt(e.detail);
      console.log(linewidth)

      this.setData({
        cLineWidth: linewidth
      })


    },
    starthb1(e) { // 画布一
      console.log(e)
      var _this = this;
      this.sx1 = e.touches[0].x;
      this.sy1 = e.touches[0].y;
      console.log(this.ctx1)
      this.ctx1.setLineWidth(this.data.cLineWidth);
      this.ctx1.setStrokeStyle(this.data.dcolor);
      this.ctx1.beginPath();
      this.ctx1.moveTo(this.sx1, this.sy1);

      _this.setData({
        moveLock: true
      })
      setTimeout(function () {
        _this.setData({
          moveLock: false
        })
      }, 300)
    },
    movehb1(e) { // 画布一
      var _this = this;

      this.mx1 = e.touches[0].x;
      this.my1 = e.touches[0].y;
      this.ctx1.lineTo(this.mx1, this.my1);
      this.ctx1.stroke();
      this.ctx1.draw(true);

      this.ctx1.moveTo(this.mx1, this.my1);
      this.setData({
        moveLock: true
      })
    },
    endhb1(e) { // 画布一
      var _this = this;
      var timer = null;
      this.ctx1.closePath();
      console.log("离开画布")

      console.log("moveLock", _this.data.moveLock)
      setTimeout(function () {
        _this.setData({
          moveLock: false
        })
      }, 150)
      if (_this.data.moveLock == false) {
        timer = setTimeout(function () {
          _this.createImg();
        }, 150)
      }
    },
    getCanvasImg() {
      var _this = this;
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1213,
        canvasId: "chuabusave",
        success: function (res) {
          console.log(res)
          _this.setData({
            getCanvas: res.tempFilePath
          })
        }
      }, this)
    },
    selToolfn(e) { // 画布工具
      console.log(e.currentTarget.dataset.sel);
      var sel = e.currentTarget.dataset.sel
      if (sel == 1) {
        console.log(this.data.dcolor)
        this.setData({
          saveColor: this.data.dcolor
        })

      }
      this.setData({
        toolSel: sel
      })
      if (sel == 1) { // 橡皮擦
        this.setData({
          dcolor: "#ffffff",
          scolor: 'none',
          showColor: false,
          xpc: true
        })
        this.ctx1.globalCompositeOperation = 'destination-out';
      } else {
        this.ctx1.globalCompositeOperation = 'source-over';
      }
      if (sel == 2) {
        var showColor = this.data.showColor
        this.setData({
          showColor: !showColor
        })


      }
      if (sel == 3) { // 选择画笔
        this.setData({
          //dcolor: "#000000",
          dcolor: this.data.saveColor,
          scolor: 'none',
          showColor: false,
          dcolorIndex: ''
        }, function () {
          this.ctx1.setStrokeStyle(this.data.dcolor);
        })
      }
    },
    closeColorboard2() {
      this.setData({
        showColor: false,
        toolSel: 3
      })
    },
    closeColorboard() {
      this.setData({
        showColor: false
      })
    },
    saveImagelx2() { // 练习二 保存图片
      var _this = this;
      this.saveImage(function () {
        _this.loadCanvasImg("saveLocal")
      })
     
    },
    getImgbase(fn) {
      var _this = this;


      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1213,
        canvasId: "chuabu1",
        success: function (res) {
          console.log(res)
          let pic = res.tempFilePath;
          var img = _this.data.newbgarr[_this.data.picNum]
          console.log("pic", pic)
          console.log("img", img)
          _this.ctx3.drawImage(img, 0, _this.data.curTop, _this.data.cwidth, _this.data.cwidth)
          _this.ctx3.drawImage(pic, 0, 0, _this.data.cwidth, _this.data.cheight)
          _this.ctx3.draw(true);
          setTimeout(function () {

            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 750,
              height: 1213,
              canvasId: "saveLocal",
              success: function (res) {
                console.log(res)
                let pic = res.tempFilePath;
                //******************************************

                wx.getFileSystemManager().readFile({   // 文件管理系统按照base64方式读取生成的图片
                  filePath: res.tempFilePath, //选择图片返回的相对路径
                  encoding: 'base64', //编码格式
                  success: res => { //成功的回调
                    var base64 = 'data:image/png;base64,' + res.data
                    if (fn) {
                      fn(base64)
                    }

                  }
                }, this)

                //******************************************* 


              }
            }, _this);




          }, 500)

        }
      }, this);



    },
    getBase64() {
      var _this = this;
      this.getImgbase(function (data) {
        console.log("图片数据")

        console.log(data)
        _this.triggerEvent("lx4Event", data)
      })

    },
    saveImage(fn) { // 打开保存图片授权
      var _this = this;
      console.log(123)
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                // 同意授权
                console.log("同意授权")
                if (fn) {
                  fn()
                }
              },
              fail: (res) => {
                console.log(res);
              }
            })
          } else {
            // 已经授权了
            console.log("已经授权了");
            if (fn) {
              fn()
            }
          }
        },
        fail: (res) => {
          console.log(res);
        }
      })
    },
    loadCanvasImg(id) {
      var _this = this;
      wx.showLoading({
        title: '保存中...',
      })

      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1213,
        canvasId: "chuabu1",
        success: function (res) {
          console.log(res)
          let pic = res.tempFilePath;
          var img = _this.data.newbgarr[_this.data.picNum]
          console.log("pic", pic)
          console.log("img", img)
          _this.ctx3.drawImage(img, 0, _this.data.curTop, _this.data.cwidth, _this.data.cwidth)
          _this.ctx3.drawImage(pic, 0, 0, _this.data.cwidth, _this.data.cheight)
          _this.ctx3.draw(true);
          setTimeout(function () {
            //******************************************
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 750,
              height: 1213,
              canvasId: "saveLocal",
              success: function (res) {
                console.log(res)
                let pic = res.tempFilePath;

                wx.saveImageToPhotosAlbum({
                  filePath: pic,
                  success(res) {
                    wx.hideLoading();
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success',
                      duration: 2000
                    });
                  },
                  complete() {
                    wx.hideLoading();
                  }
                });
              }
            }, _this);



            //******************************************* 
          }, 500)

        }
      }, this);




    },
    createImg() {
      var _this = this;
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1213,
        canvasId: "chuabu1",
        success: function (res) {
          console.log(res)
          let pic = res.tempFilePath;
          var img = _this.data.newbgarr[_this.data.picNum]
          console.log(pic)
          console.log(img)
          _this.ctx2.drawImage(img, 0, _this.data.curTop, _this.data.cwidth, _this.data.cwidth)
          _this.ctx2.drawImage(pic, 0, 0, _this.data.cwidth, _this.data.cheight)
          _this.ctx2.draw(true, function () {
            console.log(123)
            _this.getCanvasImg();
          });
          // setTimeout(function(){
          //   _this.getCanvasImg();
          // },100)
        }
      }, this);
    },
  },

})
